<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog :title="!form.jobId ? '新增' : '修改'" modal-append-to-body append-to-body width="80%"
             :visible.sync="visible">
    <el-form ref="dataForm" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="form.jobName" placeholder="请输入任务名称" maxlength="50" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务组名" prop="jobGroup">
            <el-input v-model="form.jobGroup" placeholder="请输入任务组名" maxlength="50" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="jobType">
            <el-select v-model="form.jobType" placeholder="请选择类型" clearable>
              <el-option v-for="(item,i) in jobList" :key="i" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.jobType == 3 || form.jobType == 5">
          <el-form-item label="HTTP请求类型" prop="methodType">
            <el-select v-model="form.methodType" placeholder="请选择类型" clearable>
              <el-option v-for="(item,i) in methodTypeList" :key="i" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.jobType == 3 || form.jobType == 4 || form.jobType == 5 || form.jobType == 9">
          <el-form-item label="执行路径" prop="executePath">
            <el-input v-model="form.executePath" placeholder="请输入执行路径" maxlength="200" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.jobType == 1 || form.jobType == 2 || form.jobType == 9">
          <el-form-item label="执行文件" prop="className">
            <el-input v-model="form.className" placeholder="请输入执行文件" maxlength="200" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.jobType == 1  || form.jobType == 2|| form.jobType == 9">
          <el-form-item label="执行方法" prop="methodName">
            <el-input v-model="form.methodName" placeholder="请输入执行方法" maxlength="200" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行参数值" prop="methodParamsValue">
            <el-input v-model="form.methodParamsValue" placeholder="请输入执行参数值" maxlength="200" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="cron表达式" prop="cronExpression">
            <div class="cron">
              <el-input
                v-model="form.cronExpression"
                placeholder="请输入定时策略"
                @focus="cronPopover=true"/>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="错失执行策略" prop="misfirePolicy">
            <el-select v-model="form.misfirePolicy" placeholder="请选择错失执行策略" clearable>
              <el-option v-for="(item,i) in misfireList" :key="i" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息" maxlength="300" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" icon="el-icon-circle-plus-outline" :loading="save.loading" @click="dataFormSubmit">
        {{save.text}}
      </el-button>
      <el-button icon="el-icon-circle-close" @click="visible = false">取 消</el-button>
    </div>

    <el-dialog title="选择cron表达式" modal-append-to-body append-to-body width="600px" :visible.sync="cronPopover">
      <cron i18n="cn" @change="changeCron" @close="cronPopover=false"/>

    </el-dialog>
  </el-dialog>
</template>

<script>
  import {addObj, isValidTaskName, putObj,} from '@/api/daemon/sys-job'
  import {cron} from 'vue-cron'
  import {remote} from '@/api/admin/dict'

  export default {
    name: "Menu",
    components: {cron},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 是否显示弹出层
        visible: false,

        cronPopover: false,
        form: {
          jobName: '',
          jobGroup: '',
          jobType: '1',
          executePath: '',
          className: '',
          methodType: 'POST',
          methodName: '',
          methodParamsValue: '',
          cronExpression: '',
          misfirePolicy: '',
          remark: '',
        },
        // 表单校验
        rules: {
          jobName: [
            {required: true, message: "任务名称不能为空", trigger: "blur"}
          ],
          jobGroup: [
            {required: true, message: "任务组名不能为空", trigger: "blur"}
          ],
          jobType: [
            {required: true, message: "请选择类型", trigger: "blur"}
          ],
          methodType: [
            {required: true, message: "请选择HTTP请求类型", trigger: "blur"}
          ],
          cronExpression: [
            {required: true, message: "cron表达式不能为空", trigger: "change"}
          ],
          misfirePolicy: [
            {required: true, message: "请选择错失执行策略", trigger: "blur"},
          ]
        },

        save: {
          loading: false,
          text: '保 存',
          defaultText: '保 存',
          loadingText: '正在保存'
        },
        jobList: [],
        methodTypeList: [],
        misfireList: [],
      };
    },
    watch: {
      visible(val) {
        if (!val) {
          Object.assign(this.$data, this.$options.data());
        } else {
          this.getDictList('job_type', 'jobList')
          this.getDictList('misfire_policy', 'misfireList')
          this.getDictList('method_type', 'methodTypeList')
        }
      }
    },
    created() {

    },
    methods: {
      init(isEdit, row) {
        if (row && row.jobId != null) {
          this.form.jobId = row.jobId;
        }
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (isEdit) {
            Object.keys(this.form).forEach(item => {
              this.form[item] = row[item]
            })
          }
        })
      },
      getDictList(type, item) {
        remote(type).then(response => {
          const code = response.data.code
          if (code === 0) {
            this[item] = response.data.data
          }
        })
      },
      changeCron(val) {
        this.form.cronExpression = val
      },
      // 表单提交
      dataFormSubmit() {

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.loadingSave()
            if (this.form.jobId) {
              putObj(this.form).then(() => {
                this.loadedSave()
                this.$emit('refreshDataList')
                this.visible = false
                this.$notify.success('修改成功')
              }).catch(() => {
                this.loadedSave()
              })
            } else {
              isValidTaskName({
                'jobName': this.form.jobName,
                'jobGroup': this.form.jobGroup
              }).then(response => {
                this.loadedSave()
                const result = response.data.code
                if (result !== 0) {
                  this.$notify.error('任务名称与任务组重复，请确认后重新添加')
                } else {
                  addObj(this.form).then(() => {
                    this.$notify.success('创建成功')
                    this.visible = false
                    this.$emit('refreshDataList')
                  }).catch(() => {
                    this.loadedSave()
                  })
                }
                done()
              }).catch(err => {
                this.loadedSave()
                this.$message.error(err)
              })
            }
          }
        })
      },
      // 请求中
      loadingSave() {
        this.save.loading = true
        this.save.text = this.save.loadingText
      },
      // 请求完成
      loadedSave() {
        this.save.loading = false
        this.save.text = this.save.defaultText
      },
    }
  };
</script>
